#!/usr/bin/env python
# -*- coding: utf-8 -*-

#to ensure the utf8 encoding environment
import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)
import time
from configuration import Configuration
from google.appengine.ext import db
from google.appengine.api import xmpp

weibo_bot = "weibo_bot_here"		#eg. sinat041@gmail.com
verify_code = "verify_code_here"	#eg. 69511105
twitter_id = "twitter_id_here"		#eg. moldavite

def initialized():
	try:
		c=db.GqlQuery("SELECT * FROM Configuration")
		return c.count()
	except:
		return False

def initialize():
	#do something to initialize.
	xmpp.send_invite(weibo_bot)
	time.sleep(5) # was it necessary?
	if xmpp.get_presence(weibo_bot):
		xmpp.send_message(weibo_bot, verify_code)
		c = Configuration()
		c.weibo_bot = weibo_bot
		c.twitter_id = twitter_id
		c.put()
		print """<p>Initialize completed. you can <a href="http://weibo.com/plugins/imbot/myim.php?source=toptray">check if this app is bundled to the weibo bot</a>.</p>"""
		return True
	else:
		print "<p>Error occured.</p>"
		return False

print "<html><body>"
if initialized():
	print "<p>Invalid access or app initialized.</p>"
else:
	print "<p>Start initializing...</p>"
	initialize()
print "</body></html>"